import 'package:http/http.dart' as http;
import 'package:flutter/foundation.dart';
import 'dart:convert';
import 'package:chat_msg_demo/model/message_model.dart';

class CompletionDao {
  static Future<String?> createCompleations({
    required String prompt,
    List<MessageModel>? history,
  }) async {
    try {
      final messages = <Map<String, String>>[];

      // 添加历史消息
      if (history != null) {
        for (var msg in history) {
          messages.add({
            'role': msg.ownerType == OwnerType.sender ? 'user' : 'assistant',
            'content': msg.content
                .replaceAll('\r\n', '\n')
                .replaceAll('\r', '\n'),
          });
        }
      }

      // 添加当前问题
      messages.add({
        'role': 'user',
        'content': prompt.replaceAll('\r\n', '\n').replaceAll('\r', '\n'),
      });

      debugPrint(messages.toString()  );

      final requestBody = {
        'messages': messages,
        'model': 'ep-20250305171046-hjdv5',
        'temperature': 0.7,
        'max_tokens': 2000,
      };

      debugPrint('发送请求: ${jsonEncode(requestBody)}');

      final response = await http.post(
        Uri.parse('https://ark.cn-beijing.volces.com/api/v3/chat/completions'),
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer b8907af6-ed2a-4107-9271-78697db8e746',
        },
        body: jsonEncode(requestBody),
      );

      debugPrint('响应状态码: ${response.statusCode}');
      debugPrint('响应内容: ${response.body}');

      if (response.statusCode == 200) {
        final data = jsonDecode(response.body);
        final content = data['choices'][0]['message']['content'] as String;
        return content.replaceAll('\r\n', '\n').replaceAll('\r', '\n');
      }
      return null;
    } catch (e) {
      debugPrint('错误: $e');
      return null;
    }
  }
}
